package v1

import (
	"ginblog/model"
	"ginblog/utils/errmsg"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

//查询用户身份存在
func ArticleExist(c *gin.Context) {
	title := c.Query("title")

	code := model.CheckArticle(title)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

//添加用户
func AddArticle(c *gin.Context) {
	var data model.Article
	_ = c.ShouldBindJSON(&data)

	code := model.CheckArticle(data.Title)
	if code == errmsg.SUCCESS {
		code = model.AddArticle(&data)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

//查询单个用户
func GetArticle(c *gin.Context) {
	title := c.Param("title")

	data, code := model.GetArticle(title)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
		"data":    *data,
	})
}

//查询用户列表
func GetArticles(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	page, _ := strconv.Atoi(c.Query("page"))

	if pageSize == 0 {
		pageSize = -1
	}
	if page <= 0 {
		page = -1
	}
	data, total := model.GetArticles(page, pageSize)

	code := errmsg.SUCCESS
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
		"data":    data,
		"total":    total,
	})
}

//编辑用户
func EditArticle(c *gin.Context) {
	var Article model.Article
	id, _ := strconv.Atoi(c.Param("id"))
	_ = c.ShouldBindJSON(&Article)
	code := model.CheckArticle(Article.Title)
	if code == errmsg.SUCCESS {
		code = model.EditArticle(id, &Article)
	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}

//删除用户
func DeleteArticle(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteArticle(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": errmsg.GetErrMsg(code),
	})
}
